package com.xcc.order.controller;

import com.xcc.entities.CommonResult;
import com.xcc.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@RestController
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;

//    private String REST_UTL = "http://localhost:8001"; //http调用
    //采用restTemplate的@LoadBalance调用
    private String REST_UTL = "http://CLOUD-PAYMENT-SERVICE";

    @GetMapping("/consumer/save")
    public CommonResult save(Payment payment){
        return restTemplate.postForObject(REST_UTL + "/" + "save", payment, CommonResult.class);
    }

    @GetMapping("/consumer/getById/{id}")
    public CommonResult save(@PathVariable Long id){
        return restTemplate.getForObject(REST_UTL + "/getById/"+ id, CommonResult.class);
    }

    @GetMapping("/consumer/discorver")
    public void discorver(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("instanceid:"+instance.getInstanceId()+"...serviceid:"
                    +instance.getServiceId()+"...uri:"+instance.getUri()
                    +"...shcemal:"+instance.getScheme()
            +"...metadata:"+instance.getMetadata());
        }
    }

}
